package org.dromara.business.sensitive;

import java.io.*;
import java.nio.file.*;
import java.util.*;

public class SensitiveFilter {
    private final ACAutomaton automaton = new ACAutomaton();

    public SensitiveFilter(List<String> wordList) {
        automaton.build(wordList);
    }

    public static SensitiveFilter fromFile(String path) throws IOException {
        List<String> lines = Files.readAllLines(Paths.get(path));
        return new SensitiveFilter(lines);
    }

    public boolean contains(String text) {
        return !automaton.match(text).isEmpty();
    }

    public Set<String> getMatchedWords(String text) {
        List<SensitiveWord> hits = automaton.match(text);
        Set<String> result = new HashSet<>();
        for (SensitiveWord word : hits) {
            result.add(word.getWord());
        }
        return result;
    }

    public String replace(String text, char mask) {
        return automaton.replace(text, mask);
    }

    public List<SensitiveWord> detail(String text) {
        return automaton.match(text);
    }
}
